﻿using System;
using System.Reflection;
using System.Web.Mvc;

namespace MvcSimplyCleverPart3
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class LocalizableActionNameAttribute : ActionNameSelectorAttribute
    {
        public LocalizableActionNameAttribute(Type resourceType, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Cannot be null or empty", "name");
            }

            if (resourceType == null)
            {
                throw new ArgumentNullException("resourceType");
            }

            this.Name = name;
            this.ResourceType = resourceType;
        }

        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            return string.Equals(actionName, this.LocalizedActionName, StringComparison.OrdinalIgnoreCase);
        }

        public string Name { get; private set; }

        public Type ResourceType { get; private set; }

        public string LocalizedActionName
        {
            get
            {
                return GetPropertyValue(this.ResourceType, this.Name);
            }
        }

        private static string GetPropertyValue(Type type, string propertyName)
        {
            PropertyInfo propertyInfo = type.GetProperty(propertyName, 
                BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
            if (propertyInfo == null)
            {
                return null;
            }

            return (string) propertyInfo.GetValue(null, new object[] { });
        }
    }
}